﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HiStaff.Util;
using HiStaff.Base;
using HiStaff.Control;
using HiStaff.Dal;
using HiStaff.Domain.CO;
using Janus.Windows.GridEX;
using HiStaff.Util.Enum;
using System.Collections;
namespace HiStaff.iTime
{
    public partial class ImportData : FormBase
    {
        private bool isValidImpData = true;
        private List<SY_ORGPERIOD> lstOpenOrgPeriod;
        private bool _isACVFile = false;

        private const string GCOL_SELECTOR = "SELECTOR";
        private const string GCOL_EMPLOYEEID = "EMPLOYEEID";
        private const string GCOL_EMPLOYEENAME = "EMPLOYEENAME";
        private const string GCOL_WORKINGDAY = "WORKINGDAY";
        private const string GCOL_ORGNAME = "ORGNAME";

        public ImportData()
        {
            InitializeComponent();
        }

        private void ImportData_Load(object sender, EventArgs e)
        {
            try
            {
                if (IsProcessing)
                {
                    return;
                }
                else
                {
                    IsProcessing = true;
                }

                base.CreateCommandBar(CommandBarManager.ActionCommand.ExportExcel,
                                      CommandBarManager.ActionCommand.Separator,
                                      CommandBarManager.ActionCommand.ImportExcel,
                                      CommandBarManager.ActionCommand.Separator,
                                      //CommandBarManager.ActionCommand.ImportAnotherFile,
                                      CommandBarManager.ActionCommand.Separator,
                                      CommandBarManager.ActionCommand.Save,
                                      CommandBarManager.ActionCommand.Separator,
                                      CommandBarManager.ActionCommand.Exit);

                LoadImportSignList();

                base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Save)).Enabled = Janus.Windows.UI.InheritableBoolean.False;

                IsProcessing = false;
            }
            catch (Exception ex)
            {
                IsProcessing = false;
                MessageBox.Show(ex.Message + ex.StackTrace);
                Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
            }
        }

        private void InitGrid()
        {
            GridEXColumn col;

            jgridData.FrozenColumns = 3;
            jgridData.RootTable.Columns.Clear();
            //col = new GridEXColumn();
            //col.ActAsSelector = true;
            //col.ColumnType = ColumnType.CheckBox;
            //col.EditType = EditType.CheckBox;
            //col.FilterEditType = FilterEditType.CheckBox;
            //col.Width = 20;
            //jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_EMPLOYEEID;
            col.DataMember = GCOL_EMPLOYEEID;
            col.Caption = "MÃ NHÂN VIÊN";
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.TextBox;
            col.ColumnType = ColumnType.Text;
            col.HeaderAlignment = TextAlignment.Center;
            col.Width = 80;
            jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_EMPLOYEENAME;
            col.DataMember = GCOL_EMPLOYEENAME;
            col.Caption = "TÊN NHÂN VIÊN";
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.TextBox;
            col.ColumnType = ColumnType.Text;
            col.HeaderAlignment = TextAlignment.Center;
            col.Width = 150;
            jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_ORGNAME;
            col.DataMember = GCOL_ORGNAME;
            col.Caption = "Phòng ban / bộ phận";
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.TextBox;
            col.ColumnType = ColumnType.Text;
            col.HeaderAlignment = TextAlignment.Center;
            col.Width = 150;
            //col.Selectable = false;
            jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_WORKINGDAY;
            col.DataMember = GCOL_WORKINGDAY;
            col.Caption = "NGÀY";
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.TextBox;
            col.HeaderAlignment = TextAlignment.Center;
            col.Width = 100;
            jgridData.RootTable.Columns.Add(col);

            foreach (var item in jgridSignList.GetCheckedRows())
            {
                col = new GridEXColumn();
                col.Key = ((CO_SIGN_LST)item.DataRow).WCODE;
                col.DataMember = ((CO_SIGN_LST)item.DataRow).WCODE;
                col.Caption = ((CO_SIGN_LST)item.DataRow).WCODE;
                col.HeaderStyle.TextAlignment = TextAlignment.Center;
                col.EditType = EditType.NoEdit;
                col.TextAlignment = TextAlignment.Empty;
                col.FilterEditType = FilterEditType.TextBox;
                col.ColumnType = ColumnType.Text;
                col.Width = 40;
                col.HeaderToolTip = ((CO_SIGN_LST)item.DataRow).WNAME;
                jgridData.RootTable.Columns.Add(col);
            }

            if (jgridData.DataSource != null)
            {
                jgridData.Refetch();
            }
        }

        protected override void SetStatusInputControl(System.Windows.Forms.Control container, bool status)
        {
            
        }
        protected override void SetToolStripButtonBar(CommandBarManager.ActionCommand cmd)
        {
            
        }

        protected override bool ImportExcelButtonClick()
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "XML Spreadsheet 2003 (*.xml)|*.xml";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                if (IOCommonFunction.FileInUse(openDialog.FileName))
                {
                    MessageBox.Show(string.Format(Constant.MSG_CANNOT_OPENFILE, openDialog.FileName),
                                    this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }

                _isACVFile = false;
                jgridSignList.Enabled = !_isACVFile;

                InitGrid();

                Aspose.Cells.License lc = new Aspose.Cells.License();
                string strLicense = AppDomain.CurrentDomain.BaseDirectory + "\\lib\\Aspose.Cells.lic";
                lc.SetLicense(strLicense);

                //Instantiate LoadOptions specified by the LoadFormat.
                Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                workbook.Open(openDialog.FileName);

                Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
                DataTable mv_dtDataPrepare = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow + 1, worksheet.Cells.MaxColumn + 1);

                DataRow dtRowTitle = mv_dtDataPrepare.Rows[0];
                foreach (GridEXColumn gCol in jgridData.RootTable.Columns)
                {
                    foreach (DataColumn dtCol in mv_dtDataPrepare.Columns)
                    {
                        if (gCol.Caption.Equals(dtRowTitle[dtCol]))
                        {
                            dtCol.ColumnName = gCol.Key;
                            break;
                        }
                    }
                }

                //remove first row is header row
                mv_dtDataPrepare.Rows.RemoveAt(0);

                //jgridData.SetDataBinding(mv_dtDataPrepare, string.Empty);
                jgridData.DataSource = mv_dtDataPrepare;
                jgridData.Refresh();

                isValidImpData = CheckValidData();
                if (isValidImpData)
                {
                    base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Save)).Enabled = Janus.Windows.UI.InheritableBoolean.True;
                }
                else
                {
                    base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Save)).Enabled = Janus.Windows.UI.InheritableBoolean.False;
                }
            }

            return true;
        }

        protected override bool ExportExcelButtonClick()
        {
            base.ExportExcelFromGrid(jgridData, true);
            return true;
        }

        protected override bool SaveButtonClick()
        {
            CO_DAY_RGT objInsert;
            CO_SIGN_LST objCol;
            DateTime doutval;
            decimal noutval;
            CO_ACVDATAFILE objACVImport;
            if (_isACVFile)
            {
                foreach (var item in jgridData.GetDataRows())
                {
                    objACVImport = new CO_ACVDATAFILE();

                    objACVImport.COL1 = ((DataRowView)item.DataRow)[0].ToString();
                    objACVImport.COL2 = ((DataRowView)item.DataRow)[1].ToString();
                    objACVImport.COL3 = ((DataRowView)item.DataRow)[2].ToString();
                    objACVImport.COL4 = ((DataRowView)item.DataRow)[3].ToString();
                    objACVImport.COL5 = ((DataRowView)item.DataRow)[4].ToString();
                    //objACVImport.Username = StaticObject.Username;

                    OracleHelper.ExcuteNonQuery("PKG_HCM_COLEX", "PRU_IMPFROMACVFILE", objACVImport);

                    if (!string.IsNullOrEmpty(objACVImport.ERRMSG))
                    {
                        MessageBox.Show(objACVImport.ERRMSG, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                }

                MessageBox.Show(Constant.MSG_TRANSACTION_SUCCESSFUL, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return true;
            }

            if (isValidImpData)
            {
                foreach (var drow in jgridData.GetDataRows())
                {
                    objInsert = new CO_DAY_RGT();
                    objInsert.EMPLOYEEID = drow.Cells[GCOL_EMPLOYEEID].Value.ToString();

                    if (DateTime.TryParseExact(drow.Cells[GCOL_WORKINGDAY].Value.ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out doutval))
                    {
                        objInsert.WORKINGDAY = doutval;
                    }
                    else
                    {
                        continue;
                    }

                    foreach (var dcol in jgridSignList.GetCheckedRows())
                    {
                        objCol = (CO_SIGN_LST)dcol.DataRow;

                        objInsert.WCODE = objCol.WCODE;

                        if (drow.Cells[objInsert.WCODE].Value == null)
                        {
                            MessageBox.Show(string.Format(Constant.MSG_NODATA_IMP, objInsert.WCODE), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return false;
                        }
                        switch (ConvertHelper.ConverStringToEnum<WorkSignDataType>(objCol.WDATATYEID.Value.ToString()))
                        {
                            case WorkSignDataType.DateTime:
                                if (DateTime.TryParseExact(drow.Cells[GCOL_WORKINGDAY].Value.ToString() + " " + drow.Cells[objInsert.WCODE].Value.ToString(), "dd/MM/yyyy HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out doutval))
                                {
                                    objInsert.DVALUE = doutval;
                                }
                                else
                                {
                                    objInsert.DVALUE = null;
                                }
                                objInsert.NVALUE = null;
                                objInsert.SVALUE = null;
                                break;
                            case WorkSignDataType.Number:
                                if (Decimal.TryParse(drow.Cells[objInsert.WCODE].Value.ToString(), out noutval))
                                {
                                    objInsert.NVALUE = noutval;
                                }
                                else
                                {
                                    objInsert.NVALUE = null;
                                }
                                objInsert.DVALUE = null;
                                objInsert.SVALUE = null;
                                break;
                            case WorkSignDataType.String:
                                objInsert.SVALUE = drow.Cells[objInsert.WCODE].Value.ToString();
                                objInsert.NVALUE = null;
                                objInsert.DVALUE = null;
                                break;
                            default:
                                break;
                        }

                       // objInsert.Username = StaticObject.Username;
                        objInsert.STATUS = 1;
                        OracleHelper.ExcuteNonQuery("PKG_HCM_COLEX", "PRI_DAYRGT", objInsert);
                    }
                }
                MessageBox.Show(Constant.MSG_TRANSACTION_SUCCESSFUL, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return true;
            }
            else
            {
                MessageBox.Show(Constant.MSG_INVALID_IMPDATA, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
           private bool CheckValidData()
        {
            bool returnval = true;
            DateTime doutval;
            CO_SIGN_LST objCol;
            decimal noutval;
            SY_ORGPERIOD objSearch = new SY_ORGPERIOD();
            objSearch.STATUSCOLEX = 0; //Open
            lstOpenOrgPeriod = OracleHelper.ExcuteSelectMultiObject<SY_ORGPERIOD>("pkg_hcm_list", "PRS_ORGPERIOD", objSearch);
            //objSearch.STATUSCOLEX = 2; //close
            //lstFinalCloseOrgPeriod = OracleHelper.ExcuteSelectMultiObject<ERP_SY_ORGPERIOD>(pkg_hcm_list.Name, pkg_hcm_list.PRS_ORGPERIOD, objSearch);

            foreach (var item in jgridData.GetDataRows())
            {
                if (!DateTime.TryParseExact(item.Cells[GCOL_WORKINGDAY].Value.ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out doutval))
                {
                    item.RowStyle = new GridEXFormatStyle();
                    item.RowStyle.BackColor = Color.Red;
                    returnval = false;
                    continue;
                }

                objSearch = lstOpenOrgPeriod.Find(itOpen => doutval.Date >= itOpen.STARTDATE.GetValueOrDefault(DateTime.Today).Date
                                                         && doutval.Date <= itOpen.ENDDATE.Date);
                if (objSearch == null)
                {
                    item.RowStyle = new GridEXFormatStyle();
                    item.RowStyle.BackColor = Color.Red;
                    returnval = false;
                    continue;
                }

                foreach (var dcol in jgridSignList.GetCheckedRows())
                {
                    objCol = (CO_SIGN_LST)dcol.DataRow;
                    switch (ConvertHelper.ConverStringToEnum<WorkSignDataType>(objCol.WDATATYEID.Value.ToString()))
                    {
                        case WorkSignDataType.DateTime:
                            if (item.Cells[GCOL_WORKINGDAY].Value != null)
                            {
                                if (!DateTime.TryParseExact(item.Cells[GCOL_WORKINGDAY].Value.ToString() + " " + item.Cells[objCol.WCODE].Value.ToString(),
                                                            "dd/MM/yyyy HH:mm:ss", null, System.Globalization.DateTimeStyles.None,
                                                            out doutval))
                                {
                                    item.RowStyle = new GridEXFormatStyle();
                                    item.RowStyle.BackColor = Color.Red;
                                    returnval = false;
                                    continue;
                                }
                            }
                            else returnval = false;
                            break;
                        case WorkSignDataType.Number:
                            if (item.Cells[objCol.WCODE].Value != null)
                            {
                                if (!Decimal.TryParse(item.Cells[objCol.WCODE].Value.ToString(), out noutval))
                                {
                                    item.RowStyle = new GridEXFormatStyle();
                                    item.RowStyle.BackColor = Color.Red;
                                    returnval = false;
                                    continue;
                                }
                            }
                            else returnval = false;
                            break;
                        case WorkSignDataType.String:
                            if (item.Cells[objCol.WCODE].Value != null)
                            {
                                if (item.Cells[objCol.WCODE].Value.ToString() == string.Empty)
                                {
                                    item.RowStyle = new GridEXFormatStyle();
                                    item.RowStyle.BackColor = Color.Red;
                                    returnval = false;
                                    continue;
                                }
                            }
                            else returnval = false;
                            break;
                        default:
                            break;
                    }
                }
            }

            return returnval;
        }

        private void LoadImportSignList()
        {
            CO_SIGN_LST objSearch = new CO_SIGN_LST();
            objSearch.STATUS = Convert.ToInt32(EStatus.Active);//Chỉ lấy những ký hiệu đang sử dụng
            objSearch.DATAFROMEXCEL = 1; //chi lay nhung cot du lieu import

            IList lstSign = OracleHelper.ExcuteSelectMultiObject<CO_SIGN_LST>("PKG_HCM_COLEX", "PRS_SIGN", objSearch);
            jgridSignList.SetDataBinding(lstSign, "");
        }

        private void jgridSignList_RowCheckStateChanged(object sender, RowCheckStateChangeEventArgs e)
        {
            InitGrid();
        }
    }
}
